package rpcClient

import (
	"context"
	"emsctrl/rpcclient/config"
	"emsctrl/rpcclient/svc"
	"emsctrl/rpcclient/types/iotrpc"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/discov"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
)

var configFile = flag.String("f", "conf/rpc.yaml", "the config file")
var rpcClient iotrpc.DeviceMngClient
var rpcConnect *grpc.ClientConn

func RpcStop() {
	rpcConnect.Close()
}
func RpcInit() config.Config {
	flag.Parse()
	var c config.Config
	conf.MustLoad(*configFile, &c)
	cont := svc.NewClientContext(c)
	clientConf := zrpc.RpcClientConf{Etcd: discov.EtcdConf{Hosts: cont.Config.Etcd.Hosts, Key: cont.Config.Etcd.Key}}
	//clientConf := zrpc.RpcClientConf{Target: "127.0.0.1:8080"}
	client := zrpc.MustNewClient(clientConf)
	conn := client.Conn()
	rpcConnect = conn
	tableClient := iotrpc.NewDeviceMngClient(conn)
	rpcClient = tableClient
	//for {
	//	time.Sleep(time.Second)
	//	list, err := tableClient.GetDeviceTableList(context.Background(), nil)
	//	if err != nil {
	//		fmt.Println(err)
	//	}
	//	fmt.Println(list)
	//	req := iotrpc.SetDeviceReq{}
	//	req.DevName = "PCS1:逆变器"
	//	req.RegAddr = 301
	//	req.Val = 2
	//	req.Type = 2 //遥调-2，遥控-1
	//	deviceReq, _ := tableClient.SetDeviceReq(context.Background(), &req)
	//	fmt.Println(deviceReq.Res)
	//}
	return c
}

func GetDeviceTableList() {
	list, err := rpcClient.GetDeviceTableList(context.Background(), nil)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(list)
	}
}

func SetDeviceRet(devName string, regaddr, Type int32, val float32) (string, error) {
	req := iotrpc.SetDeviceReq{}
	req.DevName = devName
	req.RegAddr = regaddr
	req.Type = Type
	req.Val = val
	deviceReq, err := rpcClient.SetDeviceReq(context.Background(), &req)
	if err != nil {
		return "", err
	}
	return deviceReq.Res, nil
}
